<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyWord" placeholder="请输入部门名称"></el-input>
				</el-form-item>
        <el-form-item>
          <el-input v-model="filters.sn" placeholder="请输入部门编号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filters.state" clearable placeholder="是否启用">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryDept">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSave(null,addForm)">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="160" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="160" sortable>
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="160" sortable>
        <template slot-scope="scope">
            <div v-if="scope.row.state == 0" slot="reference" class="name-wrapper">
              <el-tag size="medium" type="danger">禁用</el-tag>
            </div>
            <div v-if="scope.row.state == 1" slot="reference" class="name-wrapper">
              <el-tag size="medium">启用</el-tag>
            </div>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="160" sortable>
			</el-table-column>
      <el-table-column prop="dirPath" label="路径" width="160" sortable>
      </el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="160" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150" fixed="right">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="saveTitle" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off" clearable></el-input>
				</el-form-item>
        <el-form-item label="部门名字" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off" clearable></el-input>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <!-- prop="manager_id"  指向 v-model="saveForm.manager_id" 做表单验证需要保持一致-->
				<el-form-item label="管理员" prop="manager_id">
          <el-select v-model="saveForm.manager_id" clearable placeholder="请选择管理员">
            <!--
            v-for="emp in employees"  数据来源，for循环
            :key="emp.id"             关键值，确保不可重复
            :label="emp.name"         显示给用户看的
            :value="emp.id"           传入到后端的值
            style="float: left"       在左边显示
            style="float: right;      在右边显示
            -->
            <el-option
                v-for="emp in employees"
                :key="emp.id"
                :label="emp.username"
                :value="emp.id">
              <span style="float: left">{{emp.username}}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="tree"
                       :props="{
                          checkStrictly:true,// 开启关联
                          label:'name',// 显示内容
                          value:'id',// 传入后端的值
                       }"
                       clearable>
          </el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	export default {
		data() {
			return {
			  // 高级查询
				filters: {
          keyWord: '',
          sn: '',
          state: '',
				},
        // 列表
				depts: [],
				total: 0,
        currentPage: 1,// 当前页
        pageSizes: [5,10,15,20,50],
        pageSize: 10,// 页面条数
				listLoading: false,
				sels: [],//列表选中列

        // 编辑页面
				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
				saveFormRules: {// 必选警告
					// sn: [
					// 	{ required: true, message: '请输入部门编号', trigger: 'blur' }
					// ],
          // name: [
          //   { required: true, message: '请输入部门名称', trigger: 'blur' }
          // ],
          // manager_id: [
          //   { required: true, message: '请选择管理员', trigger: 'blur' }
          // ],
				},
				//编辑界面数据
				saveForm: {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null,
				},
        // 新增数据,初始化值
        addForm: {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null,
        },
        saveTitle: '',
        employees: [],// 管理员
        tree: [],// 部门树
			}
		},
		methods: {
      // 当前页改变触发事件
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepts();
			},
      // 最大页面条数改变触发事件
      handleSizeChange(val) {
        this.pageSize = val;
        this.getDepts();
      },
      // 查询
      queryDept(){
        this.currentPage = 1// 回到第一页
        this.getDepts()
      },
			// 获取用户列表
			getDepts() {
				let para = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          keyWord: this.filters.keyWord,
          sn: this.filters.sn,
          state: this.filters.state,
				};
        // 开启忙等
				this.listLoading = true;
        // 获取分页数据
        this.$http.post("/dept/query",para).then(res=>{
          this.depts = res.data.data
          this.total = res.data.total
          this.listLoading = false;
          console.log(this.depts)
        })
        // 获取部门列表
        this.$http.get("/emp/list",{}).then(res=>{
          this.employees = res.data.data
        })
        // 获取部门树
        this.$http.get("/dept/tree").then(res => {
          this.tree = res.data
        })
			},

      // 获取部门列表
      // getEmps(){
			//   this.$http.get("/emp/list",{}).then(res=>{
      //     console.log(res)
      //     this.employees = res.data.data
      //   })
      // },

      // 获取部门树
      // getDeptTree(){
      //   this.$http.get("/dept/tree").then(res => {
      //     console.log(res)
      //     this.tree = res.data
      //   })
      // },

			// 显示编辑界面
			handleSave: function (index, row) {
			  if(row.id != null){
          this.saveTitle = '修改部门信息'// id不为空，修改
        }else{
          //this.saveForm = Object.assign({},row)
          this.saveTitle = '新增部门信息'// id为空，添加
        }
        this.saveForm = Object.assign({}, row);// 初始化，克隆，拷贝
				this.saveFormVisible = true;// 关闭对话框
        // 重置表单验证
        if(this.$refs['saveForm']){
          this.$refs['saveForm'].resetFields();
        }
			},

			//保存
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = false;// 忙等
							// 克隆，如果使用赋值会触发双向绑定，在表单中修改数据，即使不保存也会修改列表中显示的值
							let para = Object.assign({}, this.saveForm);
              // 如果父类id为不为空，将部门树集合的最后一个值赋值给para的父类id，将值传入后端
              if(para.parent_id){
                // 判断为对象，将对象中最后一级赋值回去，传入后端
                if (typeof para.parent_id == "object"){
                  para.parent_id = para.parent_id[para.parent_id.length - 1]
                }
              }
							// 请求
							this.$http.put("/dept",para).then((res) => {
								this.saveLoading = false;
                if(res.data.state){
                  this.$message({
                    message: res.data.tip,
                    type: 'success'
                  });
                  this.$refs['saveForm'].resetFields();//重置表单验证
                  this.saveFormVisible = false;// 关闭模态框
                  // 修改完后刷新列表，但不返回第一页
                  // 通常查询删除返回第一页，修改新增停留在当前页
                  this.getDepts()
                }else {
                  this.$message({
                    message: res.data.tip,
                    type: 'warning'
                  });
                }
							}).catch(()=>{
                this.$message({
                  message: "已取消保存",
                });
              });

						});
					}
				});
			},

      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;// 关闭盲等
          this.$http.delete("/dept/"+row.id).then(res => {
            if(res.data.state){
              this.$message({
                message: res.data.tip,
                type: 'success'
              });
            }else {
              this.$message({
                message: res.data.tip,
                type: 'warning'
              });
            }
            this.currentPage = 1// 回到第一页
            this.queryDept()
          });
        }).catch(() => {
          this.$message({
            message: "已取消删除",
          });
        });
      },

      // 选择框改变
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// 批量删除
          this.$http.patch("/dept",ids).then(res=>{
            if(res.data.state){
              this.$message({
                message: res.data.tip,
                type: 'success'
              });
            }else {
              this.$message({
                message: res.data.tip,
                type: 'warning'
              });
            }
            this.queryDept()
          })
				}).catch(() => {
          this.$message({
            message: "已取消删除",
          });
				});
			}
		},
		mounted() {
			this.getDepts()
      //this.getEmps()
      //this.getDeptTree()
		}
	}

</script>

<style scoped>

</style>